<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>ACE Editor with SQL Syntax Validation</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.4.13/ace.js" charset="utf-8"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/node-sql-parser/3.8.0/parser.js"></script>
</head>
<body>
    <div id="editor" style="height: 400px; width: 600px;"></div>

    <script>
        var editor = ace.edit("editor");
        editor.setTheme("ace/theme/github");
        editor.session.setMode("ace/mode/sql");

        editor.setValue("SELECT * FROM user WHERE id = 1;");

        function validateSQL() {
            var code = editor.getValue();
            var parser = new window.sqlParser.Parser();
            var annotations = [];

            try {
                parser.parse(code);
            } catch (error) {
                annotations.push({
                    row: error.location.start.line - 1, // ACE 使用 0 基索引
                    column: error.location.start.column - 1,
                    text: error.message,
                    type: 'error'
                });
            }

            editor.session.setAnnotations(annotations);
        }

        // 监听编辑器内容变化
        editor.session.on('change', function() {
            validateSQL();
        });

        // 初始校验
        validateSQL();
    </script>
</body>
</html>
